package org.embedchat.protocol.codec.server;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;

import org.embedchat.protocol.Constants;
import org.embedchat.protocol.codec.AbstractMessageEncoder;
import org.embedchat.protocol.message.AbstractMessage;
import org.embedchat.protocol.message.server.ErrorMessage;

@SuppressWarnings("unchecked")
public class ErrorMessageEncoder extends AbstractMessageEncoder {

    private static final Set TYPES;

    static {
        Set types = new HashSet();
        types.add(ErrorMessage.class);
        TYPES = Collections.unmodifiableSet(types);
    }
	
	public ErrorMessageEncoder() {
		super(Constants.ERROR_MESSAGE);
	}

	@Override
    protected void encodeBody(IoSession session, AbstractMessage message,
                              ByteBuffer outBuffer) {
        ErrorMessage m = (ErrorMessage) message;
        DataOutputStream out = new DataOutputStream(outBuffer.asOutputStream());
        try {
            out.writeInt(m.getMessageCode());
            out.writeUTF(m.getErrorMessageString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Set getMessageTypes() {
        return TYPES;
    }
}
